package top.colordreams.tenant.sping.starter;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.annotation.ApplicationScope;
import org.springframework.web.context.annotation.RequestScope;
import top.colordreams.tenant.DefaultTenantContext;
import top.colordreams.tenant.TenantConfig;
import top.colordreams.tenant.TenantContext;
import top.colordreams.tenant.exception.TenantException;
import top.colordreams.tenant.resolver.CurrentTenantResolver;

import java.util.Optional;

/**
 * 动态租户自动配置
 *
 * @author 秋辞未寒
 */
@Configuration
@EnableConfigurationProperties(DynamicTenantProperties.class)
@ConditionalOnProperty(prefix = DynamicTenantProperties.PREFIX, value = "enabled", havingValue = "true")
public class DynamicTenantAutoConfiguration {

    @Bean
    @ApplicationScope
    @ConditionalOnMissingBean(TenantConfig.class)
    public TenantConfig tenantConfig(DynamicTenantProperties properties) {
        Optional<String> defaultTenantId = Optional.ofNullable(properties.getDefaultTenantId());
        Optional<String> rootTenantId = Optional.ofNullable(properties.getRootTenantId());
        boolean defaultTenantIsRoot = properties.isDefaultTenantIsRoot();

        if (defaultTenantId.isEmpty() && rootTenantId.isEmpty()) {
            throw new TenantException("`defaultTenantId`和`rootTenantId`不能同时为空");
        } else {
            if (defaultTenantId.isEmpty()) {
                defaultTenantId = rootTenantId;
            }
            if (rootTenantId.isEmpty()) {
                rootTenantId = defaultTenantId;
            }
        }

        if (!defaultTenantIsRoot && defaultTenantId.equals(rootTenantId)) {
            throw new TenantException("`defaultTenantIsRoot`为`false`时,`defaultTenantId`和`rootTenantId`不能为空且不能相同");
        }

        TenantConfig.TenantConfigBuilder configBuilder = TenantConfig.builder();
        configBuilder.defaultTenantId(defaultTenantId.get());
        configBuilder.rootTenantId(rootTenantId.get());
        configBuilder.defaultTenantIsRoot(defaultTenantIsRoot);
        return configBuilder.build();
    }

    @Bean
    @RequestScope
    @ConditionalOnMissingBean(TenantContext.class)
    public TenantContext tenantContext(TenantConfig tenantConfig, CurrentTenantResolver currentTenantResolver) {
        return new DefaultTenantContext(tenantConfig, currentTenantResolver);
    }

}
